import api from './api'
import { logger } from '@/utils/logger'

/**
 * 条文相关API服务
 */
export class ArticleService {
  // 获取条文列表
  async getArticles(params = {}) {
    try {
      logger.userAction('获取条文列表', params)
      const response = await api.get('/articles', { params })
      return {
        articles: response.data?.articles || [],
        pagination: response.data?.pagination || {},
        chapters: response.data?.chapters || []
      }
    } catch (error) {
      logger.error('获取条文列表失败:', error)
      throw error
    }
  }

  // 获取条文详情
  async getArticle(articleId) {
    try {
      console.log('[ArticleService] 开始获取条文:', articleId)
      logger.userAction('获取条文详情', { articleId })
      const response = await api.get(`/articles/${articleId}`)
      console.log('[ArticleService] 原始axios响应:', response)
      
      // 验证响应数据结构 - response已经是axios拦截器处理后的数据
      if (!response) {
        throw new Error('API响应为空')
      }
      
      console.log('[ArticleService] 返回数据:', response)
      // 直接返回axios拦截器处理后的完整响应
      return response
    } catch (error) {
      console.error('[ArticleService] API调用失败:', error)
      console.error('[ArticleService] 错误详情:', error.response?.data)
      logger.error('获取条文详情失败:', error)
      throw error
    }
  }

  // 按章节获取条文
  async getArticlesByChapter(part, chapterNumber, params = {}) {
    try {
      logger.userAction('按章节获取条文', { part, chapterNumber, params })
      const response = await api.get('/articles', {
        params: { part, chapter: chapterNumber, ...params }
      })
      return {
        articles: response.data?.articles || [],
        pagination: response.data?.pagination || {}
      }
    } catch (error) {
      logger.error('按章节获取条文失败:', error)
      throw error
    }
  }

  // 智能搜索条文
  async searchArticles(query, params = {}) {
    try {
      logger.userAction('搜索条文', { query, params })
      const startTime = performance.now()
      
      const response = await api.get('/search', {
        params: {
          q: query,
          ...params
        }
      })
      
      const endTime = performance.now()
      logger.performance('搜索条文', endTime - startTime)
      
      return {
        articles: response.data?.articles || [],
        pagination: response.data?.pagination || {},
        searchInfo: response.data?.search_info || {}
      }
    } catch (error) {
      logger.error('搜索条文失败:', error)
      throw error
    }
  }

  // 获取搜索建议
  async getSearchSuggestions(query, limit = 10) {
    try {
      logger.userAction('获取搜索建议', { query, limit })
      const response = await api.get('/search/suggestions', {
        params: { q: query, limit }
      })
      return response.data?.suggestions || []
    } catch (error) {
      logger.error('获取搜索建议失败:', error)
      throw error
    }
  }

  // 获取章节列表
  async getChapters() {
    try {
      logger.userAction('获取章节列表')
      const response = await api.get('/articles/chapters')
      return response.data?.chapters || []
    } catch (error) {
      logger.error('获取章节列表失败:', error)
      throw error
    }
  }

  // 获取收藏列表
  async getFavorites(params = {}) {
    try {
      logger.userAction('获取收藏列表', params)
      const response = await api.get('/favorites', { params })
      return {
        favorites: response.data?.favorites || [],
        pagination: response.data?.pagination || {}
      }
    } catch (error) {
      logger.error('获取收藏列表失败:', error)
      throw error
    }
  }

  // 添加收藏
  async addFavorite(articleNumber, userId = 'anonymous') {
    try {
      logger.userAction('添加收藏', { articleNumber, userId })
      const response = await api.post('/favorites', { 
        article_number: articleNumber,
        user_id: userId 
      })
      return response.data
    } catch (error) {
      logger.error('添加收藏失败:', error)
      throw error
    }
  }

  // 移除收藏
  async removeFavorite(favoriteId) {
    try {
      logger.userAction('移除收藏', { favoriteId })
      const response = await api.delete(`/favorites/${favoriteId}`)
      return response.data
    } catch (error) {
      logger.error('移除收藏失败:', error)
      throw error
    }
  }

  // 获取搜索历史
  async getSearchHistory(userId = 'anonymous', limit = 20) {
    try {
      logger.userAction('获取搜索历史', { userId, limit })
      const response = await api.get('/search/history', {
        params: { user_id: userId, limit }
      })
      return response.data || []
    } catch (error) {
      logger.error('获取搜索历史失败:', error)
      throw error
    }
  }

  // 保存搜索历史
  async saveSearchHistory(query, resultCount = 0, userId = 'anonymous') {
    try {
      logger.userAction('保存搜索历史', { query, resultCount, userId })
      const response = await api.post('/search/history', {
        user_id: userId,
        query: query,
        result_count: resultCount
      })
      return response.data
    } catch (error) {
      logger.error('保存搜索历史失败:', error)
      // 搜索历史保存失败不应该影响搜索功能，所以不抛出错误
      return null
    }
  }

  // 获取文章详情
  async getArticleByNumber(articleNumber) {
    try {
      logger.userAction('获取文章详情', { articleNumber })
      const encodedArticleNumber = encodeURIComponent(articleNumber);
      const response = await api.get(`/articles/${encodedArticleNumber}`);
      return response; // 返回完整响应对象，包含success和data字段
    } catch (error) {
      logger.error('获取文章详情失败:', error);
      throw error;
    }
  }
}

// 导出单例实例
export const articleService = new ArticleService()

export default articleService
